package com.wzu.springbootcrud2.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzu.springbootcrud2.dao.BillMapper;
import com.wzu.springbootcrud2.dao.ProviderMapper;
import com.wzu.springbootcrud2.dao.UserMapper;
import com.wzu.springbootcrud2.pojo.Bill;
import com.wzu.springbootcrud2.pojo.Mima;
import com.wzu.springbootcrud2.pojo.Provider;
import com.wzu.springbootcrud2.pojo.User;
import com.wzu.springbootcrud2.utils.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserAction {

    @Autowired
    UserMapper userMapper;

    @Autowired
    ProviderMapper providerMapper;

    @Autowired
    BillMapper billMapper;

    int nowPage;


//    @RequestMapping("/login")
//    public String login(User user, HttpSession session){
//        System.out.println(user.getUsercode() + "--"+user.getUserpassword());
//        User u = userMapper.getLoginUser(user);
//        if (u != null){
//            session.setAttribute("userinfo", u);
//            return "index";
//        }
//        return "login";
//    }
@RequestMapping(value = "/loginpage")
public String loginpage(User user, HttpSession session, HttpServletResponse response) {
    return "loginpage";
}

@RequestMapping(value = "/login")
public String login(User user, HttpSession session, HttpServletResponse response) throws IOException {
    System.out.println(user.getUsercode() + "--"+user.getUserpassword());
    String md5 = MD5.getMD5(user.getUserpassword());
    user.setUserpassword(md5);
    response.setCharacterEncoding("utf8");
    try{
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(user.getUsercode(), user.getUserpassword()));

        User u = userMapper.getLoginUser(user);
        if (u != null){
            session.setAttribute("userinfo", u);
            return "index";
        }
    }catch (UnknownAccountException e) {
        e.printStackTrace();
        response.getWriter().write( "<script>alert('用户名错误，请重新输入！');</script>");

    } catch (IncorrectCredentialsException e) {
        e.printStackTrace();
        response.getWriter().write( "<script>alert('密码错误，请重新输入！');</script>");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
    return "loginpage";
}


    @RequestMapping("/tuichu")
    public String tuichu(User user, HttpSession session){
        System.out.println("退出系统成功");
        session.removeAttribute("userinfo");
        return "forward:/user/loginpage";
    }

    @PostMapping("/modifypsw")
    public String pswmodify(@RequestBody Mima mima, HttpSession session){
        User user = (User) session.getAttribute("userinfo");
        if (MD5.getMD5(mima.getSelfpsw()).equals(user.getUserpassword())){
            user.setUserpassword(MD5.getMD5(mima.getNewpsw()));
            userMapper.updateByPrimaryKey(user);
            System.out.println(user);
        }
        return "index";
    }


    @RequestMapping("/frame")
    public String hostpage(User user, HttpSession session){
        return "frame";
    }

    @RequestMapping("/index")
    public String Index(User user, HttpSession session){
        if (session.getAttribute("userinfo")!=null){
            return "index";
        }
        return "loginpage";
    }
//。。。。。。。。。。。。。。。。。。。。。。provider。。。。。。。。。。。。。。。。。。。。。。。。。
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @RequestMapping("/providerlist")
    public String providerlist(Model model,
                               @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session){

        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        List<Provider> pro = providerMapper.selectAll();
        PageInfo page = new PageInfo(pro, 5);
        model.addAttribute("pageInfo", page);

        System.out.println("PageInfo_findAllprovider");
        return "providerlist";
    }
//查询分页
@RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("/selectproviderbykey")
    public String selectproviderbykey(Model model,@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam("queryProCode") String code, @RequestParam("queryProName") String name){
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        Provider pro=new Provider();
        pro.setProCode(code);
        pro.setProName(name);
        List<Provider> res=providerMapper.findprobyCodeAndName(pro);
        PageInfo page = new PageInfo(res, 5);
        model.addAttribute("pageInfo", page);
        System.out.println("查询成功");
        return "providerlist";
    }


    //根据页码显示结果
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("providerlist/{pn}")
    public String findAllEmp(Model model,
                             @PathVariable Integer pn){
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        List<Provider> allEmpes = providerMapper.selectAll();
        PageInfo page = new PageInfo(allEmpes, 5);
        model.addAttribute("pageInfo", page);
        return "providerlist";
    }


    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("/provideradd")
    public String providerReturnadd(){

        return "addprovider";
    }
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @PostMapping("/provideradd")
    public String provideradd(Provider provider){
    provider.setCreationDate(new Date().toString());
        providerMapper.add(provider);
        System.out.println("添加成功post");
        return "forward:/user/providerlist";
    }
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("/viewProvider/{id}")
    public String viewProvider(@PathVariable Integer id, HttpSession session){
        Provider pro=providerMapper.getProviderById(id);
        System.out.println(pro);
        session.setAttribute("provider",pro);
        return "providerview";
    }
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("/modifyProvider/{id}")
    public String modifyProvider(@PathVariable Integer id, HttpSession session){

        Provider pro=providerMapper.getProviderById(id);
        session.setAttribute("provider",pro);
        return "providermodify";
    }
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @PostMapping("/modifyProvider")
    public String modifyProvider(Provider provider){
        System.out.println(provider);
        providerMapper.modify(provider);
        System.out.println("修改成功post");
        return "forward:/user/providerlist";
    }
    @RequiresRoles(value = {"1","2"},logical = Logical.OR)
    @GetMapping("/deleteProvider/{id}")
    public String deleteProvider(@PathVariable Integer id){

        providerMapper.deleteProviderById(id);
        System.out.println("修改成功post");
        return "forward:/user/providerlist";
    }
//............................User...................................................
@RequiresRoles(value = {"1"},logical = Logical.OR)
@RequestMapping("/userlist")
public String userlist(Model model,
                           @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session){

    PageHelper.startPage(pn, 5); //紧接着的查询会被分页
    nowPage=pn;
    List<User> user = userMapper.selectAll();
    PageInfo page = new PageInfo(user, 5);
    model.addAttribute("pageInfo2", page);

    return "userlist";
}
    //查询分页
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("/selectuserbykey")
    public String selectuserbykey(Model model,@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam("queryname") String name, @RequestParam("queryUserRole") Integer userRole){
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页

        nowPage=pn;
        User user=new User();
        user.setUsercode(name);
        user.setUserrole(userRole);
        List<User> res= userMapper.finduserbyNameAndrole(user);
        PageInfo page = new PageInfo(res, 5);
        model.addAttribute("pageInfo2", page);
        System.out.println("用户查询成功");
        return "userlist";
    }


    //根据页码显示结果
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("userlist/{pn}")
    public String findAlluser(Model model,
                             @PathVariable Integer pn){
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        List<User> allusers = userMapper.selectAll();
        PageInfo page = new PageInfo(allusers, 5);
        model.addAttribute("pageInfo2", page);
        return "userlist";
    }
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("/useradd")
    public String userReturnadd(){

        return "adduser";
    }
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @PostMapping("/useradd")
    public String useradd(User user, BindingResult bindingResult){

        if (userMapper.selectByUsercode(user.getUsercode())!=null){
            return "forward:/user/error";
        }

        String salt="asdwqAsd12_qS";
        user.setSalt(salt);
        System.out.println(user);
        String md5password= MD5.getMD5(user.getUserpassword());

        user.setUserpassword(md5password);
        userMapper.insert(user);
        return "forward:/user/userlist";
    }

    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("/viewUser/{id}")
    public String viewUser(@PathVariable Integer id, HttpSession session){
        User user=userMapper.selectByPrimaryKey(id);

        session.setAttribute("user",user);
        return "userview";
    }
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("/modifyUser/{id}")
    public String modifyUser(@PathVariable Integer id, HttpSession session){

        User user=userMapper.selectByPrimaryKey(id);
        session.setAttribute("user",user);
        return "usermodify";
    }
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @PostMapping("/modifyUser")
    public String modifyUser(User user){
        System.out.println(user);
        userMapper.updateByPrimaryKey(user);

        System.out.println("用户修改成功post");
        return "forward:/user/userlist";
    }
    @RequiresRoles(value = {"1"},logical = Logical.OR)
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable Integer id){
        userMapper.deleteByPrimaryKey(id);
        System.out.println("删除成功");
        return "forward:/user/userlist";
    }


//................................Bill..........................................................

@RequestMapping("/billlist")
public String billlist(Model model,
                       @RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session){
    List<Provider> providerLists=providerMapper.selectAll();
    model.addAttribute("providerLists",providerLists);
    PageHelper.startPage(pn, 5); //紧接着的查询会被分页
    nowPage=pn;
    List<Bill> user = billMapper.selectall();
    PageInfo page = new PageInfo(user, 5);
    model.addAttribute("pageInfo3", page);
    return "billlist";
}
    //查询分页
    @GetMapping("/selectbillbykey")
    public String selectbillbykey(Model model,@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam("queryProductName") String name, @RequestParam("queryProviderId") Integer id,@RequestParam("queryIsPayment") Integer ispay){

        List<Provider> providerLists=providerMapper.selectAll();
        model.addAttribute("providerLists",providerLists);
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        Bill bill=new Bill();
        bill.setProductname(name);
        bill.setProviderid(id);
        bill.setIspayment(ispay);
        List<Bill> res =billMapper.findBillbyNameAndIdPay(bill);
        PageInfo page = new PageInfo(res, 5);
        model.addAttribute("pageInfo3", page);
        System.out.println("订单查询成功");
        return "billlist";
    }


    //根据页码显示结果
    @GetMapping("billlist/{pn}")
    public String findAllbill(Model model,
                              @PathVariable Integer pn){
        PageHelper.startPage(pn, 5); //紧接着的查询会被分页
        nowPage=pn;
        List<Bill> allbills = billMapper.selectall();
        PageInfo page = new PageInfo(allbills, 5);
        model.addAttribute("pageInfo3", page);
        return "billlist";
    }

    @GetMapping("/billadd")
    public String billReturnadd(Model model){
        List<Provider> providerLists=providerMapper.selectAll();
        model.addAttribute("providerLists",providerLists);
        return "addbill";
    }

    @PostMapping("/billadd")
    public String billadd(Bill bill, BindingResult bindingResult){
    System.out.println(bill.getCreationdate());
    Date date=new Date();
    bill.setCreationdate(date.toString());
        billMapper.insert(bill);

        return "forward:/user/billlist";
    }


    @GetMapping("/viewBill/{id}")
    public String viewBill(@PathVariable Integer id, HttpSession session){
        Bill bill=billMapper.selectByPrimaryKey(id);
        session.setAttribute("bill",bill);
        return "billview";
    }

    @GetMapping("/modifyBill/{id}")
    public String modifyBill(Model model,@PathVariable Integer id, HttpSession session){
        List<Provider> providerLists=providerMapper.selectAll();
        model.addAttribute("providerLists",providerLists);

        Bill bill=billMapper.selectByPrimaryKey(id);

        session.setAttribute("bill",bill);
        return "billmodify";
    }
    @PostMapping("/modifyBill")
    public String modifyBill(Bill bill, BindingResult bindingResult){
        System.out.println(bill);
        billMapper.updateByPrimaryKey(bill);

        System.out.println("订单修改成功post");
        return "forward:/user/billlist";
    }
    @GetMapping("/deleteBill/{id}")
    public String deleteBill(@PathVariable Integer id){
        billMapper.deleteByPrimaryKey(id);
        System.out.println("删除成功");
        return "forward:/user/billlist";
    }

}
